package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.config.PageInfo;
import cn.wolfcode.rbac.enums.BizExceptionEnum;
import cn.wolfcode.rbac.exception.CustomException;
import cn.wolfcode.rbac.mapper.DepartmentMapper;
import cn.wolfcode.rbac.model.DepartmentDO;
import cn.wolfcode.rbac.request.DepartmentRequest;
import cn.wolfcode.rbac.service.DepartmentService;
import cn.wolfcode.rbac.vo.DepartmentVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lu.F
 * @version 1.0
 * @Description TODO
 * @date 2022/5/14 15:46
 */
@Service
@Slf4j
public class DepartmentImpl implements DepartmentService {


    @Autowired
    private DepartmentMapper departmentMapper;


    /**
     * 查询所有部门信息
     *
     * @return
     */
    @Override
    public List<DepartmentDO> selectAll() {
        return departmentMapper.selectList(null);
    }

    /**
     * 根据主键查询部门信息
     *
     * @param id
     * @return
     */
    @Override
    public DepartmentDO selectByPrimaryKey(Long id) {
        return departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("id", id));
    }

    /**
     * 添加部门信息，开启事务
     *
     * @param departmentRequest
     * @return
     */
    @Transactional
    @Override
    public int insert(DepartmentRequest departmentRequest) {

        log.info("部门对象{}", departmentRequest);
        // 请求体验证
        checkObj(departmentRequest);
        //验证部门名称是否存在
        if (checkUnique(departmentRequest.getName())) {
            DepartmentDO departmentDO = new DepartmentDO();
            departmentDO.setName(departmentRequest.getName());
            departmentDO.setSn(departmentRequest.getSn());
            return departmentMapper.insert(departmentDO);
        }

        throw new CustomException(BizExceptionEnum.OBJECT_IS_EXISTS);
    }

    /**
     * 修改或者新增部门信息
     * @param departmentRequest
     */
    public void saveOrUpdate(DepartmentRequest departmentRequest){

        Long id = departmentRequest.getId();
        DepartmentDO departmentDO = departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("id", id));
        if(departmentDO == null){
            DepartmentDO departmentDO1 = new DepartmentDO();
            BeanUtils.copyProperties(departmentRequest,departmentDO1);
            departmentMapper.insert(departmentDO1);
        }else {
            BeanUtils.copyProperties(departmentRequest,departmentDO);
            departmentMapper.update(departmentDO, new QueryWrapper<DepartmentDO>().eq("id", id));
        }
    }

    /**
     * 部门名称唯一性校验
     *
     * @param name
     * @return
     */
    private boolean checkUnique(String name) {
        DepartmentDO departmentDO = departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("name", name));
        return departmentDO == null;
    }

    /**
     * 修改部门信息
     *
     * @param departmentRequest
     * @return
     */
    @Transactional
    @Override
    public int updateByPrimaryKey(DepartmentRequest departmentRequest) {

        // 请求体验证
        checkObj(departmentRequest);
        long id = departmentRequest.getId();

        // 验证更新对象是否存在
        checkObj(selectByPrimaryKey(id));
        DepartmentDO departmentDO = DepartmentDO.builder()
                .id(departmentRequest.getId())
                .name(departmentRequest.getName())
                .sn(departmentRequest.getSn()).build();

        int row = departmentMapper.update(departmentDO, new QueryWrapper<DepartmentDO>().eq("id", id));

        return row;
    }


    /**
     * 根据主键删除部门信息
     * @param id
     * @return
     */
    @Override
    public int deleteByPrimaryKey(long id) {
        int row = departmentMapper.deleteById(id);
        return row;
    }


    /**
     * 分页显示部门信息
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<DepartmentVO> pageDepartment(int page, int size) {

        Page<DepartmentDO> pageInfo = new Page<>(page,size);
        IPage<DepartmentDO> departmentDOPage = departmentMapper.selectPage(pageInfo,new QueryWrapper<DepartmentDO>());
//        Map<String,Object> map =  new HashMap<>(4);
        /*
        map.put("page_size",size);
        map.put("current_page",page);
        map.put("total_page",departmentDOPage.getPages());
        map.put("total_records",departmentDOPage.getTotal());
        map.put("current_data",departmentDOPage.getRecords().stream().map(obj->{
            DepartmentVO departmentVO = new DepartmentVO();
            BeanUtils.copyProperties(obj,departmentVO);
            return departmentVO;
        }).collect(Collectors.toList()));
        */
        PageInfo<DepartmentVO> doPageInfo = new PageInfo<>();
        doPageInfo.setPage(page);
        doPageInfo.setTotalPage(departmentDOPage.getPages());
        doPageInfo.setSize(size);
        doPageInfo.setTotalRecords(departmentDOPage.getTotal());
        doPageInfo.setCurrentData(departmentDOPage.getRecords().stream().map(obj->{
            DepartmentVO departmentVO = new DepartmentVO();
            BeanUtils.copyProperties(obj,departmentVO);
            return departmentVO;
        }).collect(Collectors.toList()));
        return doPageInfo;
    }

    /**
     * 检查对象是否为空
     *
     * @param obj
     */
    private void checkObj(Object obj) {
        if (obj == null) {
            throw new CustomException(BizExceptionEnum.OBJECT_IS_NULL);
        }
    }
}
